<?php
namespace app\Exception;

use think\exception\Handle;
// use app\Exception\BaseException;
use think\exception\HttpResponseException;
use think\Response;
use Throwable;
use think\facade\Env;
use think\facade\Log;


class ExceptionHandle extends Handle
{
    public $status;      // HTTP请求状态码
    public $errorMsg;    // 错误信息
    public $errorCode;   // 错误码

    public function render($request, Throwable $e):Response
    {
        if($e instanceof BaseException){
            $this->status = $e->status;
            $this->errorMsg = $e->errorMsg;
            $this->errorCode = $e->errorCode;
        }else{
            if(Env::get('APP_DEBUG')) return parent::render($request, $e);

            $this->status = 500;
            $this->errorMsg = '服务器异常';
            $this->errorCode = 99999;

            $request = \think\facade\Request::instance();
            $this->recordErrorLog($e, $request->url());
        }
        
        $result = [
            'message' => $this->errorMsg,
            'error_code' => $this->errorCode
        ];

        return json($result, $this->status);

        // $response = Response::create($result, 'json', $this->status);
        // throw new HttpResponseException($response); 
    }

    /*
     * 将异常写入日志
     */
    private function recordErrorLog(Throwable $e, $uri)
    {
        Log::init([
            'type'   => 'File',
            'level'  => ['error','sql']
        ]);
        
        $str = PHP_EOL .  'msg ：' . $e->getMessage(). PHP_EOL . 
                'file：' .$e->getFile(). PHP_EOL . 
                'line：' .$e->getLine(). PHP_EOL . 
                'uri：' . $uri . PHP_EOL .
                'trace：' . $e->getTraceAsString();

        Log::write($str, 'error');
    }
}